package com.gesturesoft.imultimax.views.renderers
{
	import assets.images.hdpi.add_radio_icon;
	
	import com.adobe.crud.model.AutoCompleteNewItemModel;
	import com.gesturesoft.imultimax.events.AddEntryEvent;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import mx.events.FlexEvent;
	
	import spark.components.IconItemRenderer;
	import spark.components.TextInput;

	public class MultiSelectListNewItemRenderer extends IconItemRenderer
	{

		protected var textInputDisplay:TextInput;

		/**
		 * Constructor
		 */
		public function MultiSelectListNewItemRenderer()
		{
			super();


			iconFunction = customIconFunction;
			percentWidth = 100;

			// Add listeners
			addListeners();
		}


		//
		// Private Methods
		//

		private function addListeners():void
		{
			addEventListener(MouseEvent.CLICK, mouseClickHandler, false, 0, true);
		}



		protected function customIconFunction(item:Object):Object
		{
			if (!item)
			{
				return null;
			}

			if (item is AutoCompleteNewItemModel)
			{
				return add_radio_icon;
			}

			return null;

		}

		//--------------------------------------------------------------------------
		//
		//  Overridden methods: UIComponent
		//
		//--------------------------------------------------------------------------


		/**
		 *  @private
		 */
		override protected function createChildren():void
		{
			super.createChildren();

			// create any children you need in here

			// iconDisplay, messageDisplay, and decoratorDisplay are created in 
			// commitProperties() since they are dependent on 
			// other properties and we don't always create them
			// labelText just uses labelElement to display its data

			if (!textInputDisplay)
			{
				textInputDisplay = new TextInput();
				textInputDisplay.visible = false;
				textInputDisplay.addEventListener(FlexEvent.ENTER, enterHandler, false, 0, true);

				addChild(textInputDisplay);
			}

		}

		override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
		{
			super.updateDisplayList(unscaledWidth, unscaledHeight);

			textInputDisplay.setLayoutBoundsPosition(labelDisplay.x, 0);
			textInputDisplay.setLayoutBoundsSize(unscaledWidth - labelDisplay.x, unscaledHeight);
		}

		//
		// Event Handlers
		//

		protected function mouseClickHandler(event:MouseEvent):void
		{
			textInputDisplay.visible = true;
		}

		protected function enterHandler(event:FlexEvent):void
		{
			var evt:Event = new AddEntryEvent(textInputDisplay.text);

			dispatchEvent(evt);
			textInputDisplay.text = "";
			textInputDisplay.visible = false;

		}



	}
}